// 开启加载UI
function startLoadSpinner(){
    $('#searchAlertPlaceholder').html(`
        <div class="spinner-border text-center" role="status">
        <span class="visually-hidden">Loading...</span>
    </div>`)
}
// 关闭加载UI
function stopLoadSpinner(){
    $('#searchAlertPlaceholder').html(``)
}
// 搜索供应商
function searchProvider(){
    location.href = updateCurrentUrlParam('name', $('#input-search-provider').val())
}
// 更新供应商信息
function updateProvider(){
    let reqData = $('#form-provider-modify').serialize()
    $.ajax({
        url: '/admin/provider/update',
        type: 'POST',
        data: decodeURI(reqData),
        dataType:'json',
        error: (err) => {
            console.error(err.responseText)
        },
        success: (data) => {
            open_toast(data['code'] === 1 ? 'success' : 'fail', data['message'])
        }
    })
}
// 选中所有供应商
function choseAll(){
    $('.cb_provider').prop('checked', $('#cb_all').prop('checked') === true)
}
// 添加供应商
function addProvider(){

    $.ajax({
        url: '/admin/provider/add',
        type: 'POST',
        data: $('#form-provider-add').serialize(),
        dataType: 'JSON',
        error: (err) => {
            console.error(err.responseText)
        },
        success: (data) => {
            open_toast((data['code'] === 1)?'success':'fail', data['response'])
        }
    })
}
// 删除单个供应商
function removePorvider(id){
    if(!confirm('确定要删除该供应商吗？这将导致其相关的所有商品也被删除!')) return
    let reqData = new Map()
    reqData['ids'] = [id]
    $.ajax({
        url: '/admin/provider/delete',
        type: 'POST',
        data: JSON.stringify(reqData),
        dataType: 'JSON',
        contentType: "application/json;charset=utf-8",
        error: (err) => {
            console.error(err.responseText)
        },
        success: (data) => {
            if (data['code'] === 1) {
                open_toast('success', data['response'])
            }
        }
    })
}
// 删除多个供应商
function removeProviders(){
    if(!confirm('确定要删除该供应商吗？这将导致其相关的所有商品也被删除!')) return
    let reqData = new Map()
    // 获取当前选中的用户
    let providers = []
    // 获取选中的所有用户code
    $('.cb_provider').each(function(){
        if($(this).prop('checked') === true)
            providers.push($(this).data('id'))
    })
    reqData['ids'] = providers
    $.ajax({
        url: '/admin/provider/delete',
        type: 'POST',
        data: JSON.stringify(reqData),
        dataType: 'JSON',
        contentType: "application/json;charset=utf-8",
        error: (err) => {
            console.error(err.responseText)
        },
        success: (data) => {
            if (data['code'] === 1) {
                open_toast('success', data['response'])
            }
        }
    })

}
// 渲染模态框
function renderModal(provId){
    // 获取供应商信息
    $.ajax({
        url: '/admin/provider/query/' + provId,
        type: 'POST',
        dataType: 'JSON',
        error: (err) => {
            console.error(err.responseText)
        },
        success: (data) => {
            if (data['code'] === 1) {
                prov = data['response']
                console.log(data)
                $('#form-id').val(prov.id)
                $('#form-code').val(prov.code)
                $('#form-name').val(prov.name)
                $('#form-contact').val(prov.contact)
                $('#form-fax').val(prov.fax)
                $('#form-phone').val(prov.phone)
                $('#form-address').val(prov.address)
                $('#form-detail').val(prov.detail)
                $('#btn-modal-ok').onclick = `updateProvider(${prov.id})`
            } else
                open_toast('fail', '获取供应商信息失败!')
        }
    })
}
// 渲染供应商信息
function renderProvider(provInfo){
    $('#tbody-provider').html('')
    $.each(provInfo, (index, prov)=>{
        $('#tbody-provider').append(`
                <tr valign="baseline">
                <td><input type="checkbox" class="cb_provider" data-id="${prov['id']}"></td>
                <td>${prov['id']}</td>
                <td>${prov['code']}</td>
                <td>${prov['name']}</td>
                <td>${prov['detail']}</td>
                <td>${prov['contact']}</td>
                <td>${prov['phone']}</td>
                <td>${prov['address']}</td>
                <td>${prov['fax']}</td>
                <td>
                     <button class="btn btn-primary" onclick="renderModal('${prov['id']}')" data-bs-toggle="modal" data-bs-target="#div-modal">编辑</button>
                     <button class="btn btn-warning" onclick="removePorvider(${prov['id']})">删除</button>
                </td>
          </tr>`)
    })
}

// 渲染分页信息
function renderPage(pageInfo){
    $('#div-admin-provider-page').html('')
    // 首先设置每一页的HTML
    let $perPageInfo = $('<li></li>')
    for (let i in `${pageInfo.navigatepageNums}`) {
        if(i === '0') continue
        $perPageInfo.append(`
        <li>
            <a
                href="${updateCurrentUrlParam('pageNow', i)}" 
                class="page-link d-block text-dark ${i == pageInfo.pageNum ? ' bg-primary' : ''}">
                ${i}
            </a>
        </li>
        `)
    }
    // 如果页数大于1在进行渲染
    if(pageInfo.pages > 1){
        $('#div-admin-provider-page').html(`
     <!-- 分页部分 -->
    <h1 class="u-text-sm text-center">第${pageInfo.pageNum}页 共${pageInfo.pages}页</h1>
    <nav aria-label="Page navigation" class="u-text-sm">
        <ul class="pagination justify-content-center">
            <!--首页-->
            <li class="page-item">
                <a class="page-link d-block text-dark" href="${updateCurrentUrlParam('pageNow', pageInfo.navigateFirstPage)}">
                    首页
                </a>
            </li>
            <!--上一页-->
            <li class="page-item">
                <a class="page-link d-block text-dark"
                   href="${updateCurrentUrlParam('pageNow', pageInfo.prePage)}" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>`
            + $perPageInfo.html() +
            `
            <!--下一页-->
            <li class="page-item">
                <a class="page-link d-block text-dark"
                   href="${updateCurrentUrlParam('pageNow', pageInfo.nextPage)}" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
            <!--最后一页-->
            <li class="page-item">
                <a class="page-link d-block text-dark"
                   href="${updateCurrentUrlParam('pageNow', pageInfo.navigateLastPage)}">
                    末页
                </a>
            </li>
        </ul>
    </nav>`)
    }

    $('#textShowResult').html(`共${pageInfo.total}条结果`)
}
// 加载所有供应商信息
function loadProviderData(){
    startLoadSpinner()
    $.ajax({
        url: '/admin/provider/query',
        type: 'POST',
        data: getUrlParamToJSON(),
        dataType: 'JSON',
        contentType: 'application/json;charset=utf-8',
        error: (err)=>{
            open_toast('fail', '获取供应商信息失败.')
            console.error(err.responseText)
        },
        success: (data) =>{
            console.log(data)
            setTimeout(function (){
                if(data['code'] === 1){
                    renderProvider(data['response']['pageInfo']['list'])
                    renderPage(data['response']['pageInfo'])
                    stopLoadSpinner()
                }
            },300)
        }
    })
    $("#input-search-provider").focus()
}

// 成功弹窗出现后关闭模态框
$('#toast-success').bind('hidden.bs.toast', function () {
    $('#btn-modal-cancel').click()
    location.reload()
})
// 按键监听
$(document).keydown(function(event){
    if (event.keyCode === 13) {//回车键登陆
        $('#btn-search-provider').click()
    }
});
loadProviderData()
